﻿using ECMS.Infrastructure.Provider.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using ECMS.Infrastructure.Domain;
using System.Linq;
using System.Linq.Expressions;

namespace ECMS.Infrastructure.Provider.Implements
{
    public class ServiceCore<T> : IServiceCore<T> where T : EntityCore
    {

        protected readonly DbSet<T> _entities;
        protected readonly UnitOfWork _unitofwork;
        public ServiceCore(DbContext context)
        {
            _unitofwork = new UnitOfWork();
            _entities = context.Set<T>();
            _unitofwork.DbContext = context;
        }


        public void DeleteForge(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            entity.IsDelete = true;
            entity.LastChangeTime = DateTime.Now;
            _unitofwork.RegisterDirty(entity);
        }


        public IQueryable<T> Query(bool isFilter = true)
        {
            return isFilter ? _entities.AsTracking().Where(p => p.IsDelete == false) : _entities.AsTracking();
        }

        public void DeleteForge(Expression<Func<T, bool>> express)
        {
            var entity = Query(false).Where(express).FirstOrDefault();
            if (entity != null)
                DeleteForge(entity);

        }
        public void Delete(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));
            _unitofwork.RegisterDeleted(entity);

        }
        public void Delete(Expression<Func<T, bool>> express)
        {
            var entities = Query().Where(express).ToList();
            if (entities != null && entities.Count > 0)
                entities.ForEach(((entity) => Delete(entity)));
        }
    }
}
